<?php

namespace App\Http\Controllers\Admin;

use App\Http\Common\Lib\Common;
use App\Models\LotteryRecord;
use App\Models\Match;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class LotteryController extends BaseAdminController
{
	//
	private $model;

	public function __construct()
	{
		parent::__construct();
		$this->model = new Match();
	}

	public function index()
	{
		if (\request()->ajax()) {
			$page = \request()->input('page', 1);
			$pageSize = \request()->input('pageSize', 20);
			$search = \request()->input('search', '');
			$session = \request()->input('session', null);

			$where = [
				['and' => ['status', '>', -1]],
			];
			if ($search) {
				$where[] = ['like' => ['host|guest', '%' . $search . '%']];
			} else {
				if (!$session) {
					$session = date('Ymd');
				}
			}
			if ($session) {
				$where[] = ['and' => ['session', '=', $session]];
			}
			$order = [
				'status' => 'desc',
				'session' => 'desc',
				'number' => 'asc',
			];
			$pageData = $this->model->getPages($page, $pageSize, $where, '*', $order, 'league');
			if ($pageData['data']['pages']) {
				foreach ($pageData['data']['pages'] as $value) {
					$lastTime = strtotime($value->session) + 3600 * 24 - 60 * 5;
					$value->die_time = ($value->die_time > $lastTime) ? $lastTime : $value->die_time;
					$value->die_time = date('Y-m-d H:i', $value->die_time);
					$value->result = explode(',', $value->result);
					$league = $value->league;
					$value->league_name = '';
					if ($league) {
						$value->league_name = $league->name;
					}
					unset($value->league);
				}
			}
			return response()->json(['status' => $pageData['status'], 'msg' => $pageData['msg'], 'page' => $page, 'totalCount' => $pageData['data']['totalCount'], 'pages' => $pageData['data']['pages']]);
		} else {
			return view('admin.match.index');
		}
	}

	/**
	 * 添加比赛
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
	 */
	public function add()
	{
		return view('admin.match.add');
	}

	public function addStore()
	{
		$input = \request()->all();
		$input['status'] = 2;
		$res = $this->model->add($input);
		return response()->json(Common::dataFormat($res['status'], $res['msg'], $res['data']));

	}

	/**
	 * 编辑比赛
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
	 */
	public function edit()
	{
		return view('admin.match.edit');
	}

	/**
	 * 修改比赛比分
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function editStore()
	{
		$input = \request()->all();
		$res = $this->model->edit($input);
		return response()->json(Common::dataFormat($res['status'], $res['msg'], $res['data']));
	}

	/**
	 * 设置比分
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function setScore()
	{
		$id = \request()->input('id', 0);
		$score = \request()->input('score', '');
		$res = $this->model->setScore($id, $score);
		return response()->json(Common::dataFormat($res['status'], $res['msg'], $res['data']));
	}

	/**
	 * 修改状态
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function setStatus()
	{
		$id = \request()->input('id', 0);
		$opt = \request()->input('opt', '');
		$res = $this->model->setStatus($id, $opt);
		return response()->json(Common::dataFormat($res['status'], $res['msg'], $res['data']));
	}

	/**
	 * 比赛详情
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function getMatchDetail()
	{
		$id = \request()->input('id', 0);
		$res = $this->model->getDetail($id);
		return response()->json(Common::dataFormat($res['status'], $res['msg'], $res['data']));
	}

	/**
	 * 通过session与number获取比赛数据
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function getMatch()
	{
		$number = \request()->input('number', 0);
		$session = \request()->input('session', 0);
		if (!$session) {
			$session = date('Ymd');
		}
		$matches = $this->getCacheMatch($session);
		if ($matches) {
			$match = $matches->where('number', $number)->first();
		} else {
			$match = [];
		}
		if ($match) {
			return response()->json(Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), $match));
		} else {
			return response()->json(Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound')));
		}
	}

	/**
	 * 更新比赛数据
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function updateMatch()
	{
		$session = \request()->input('session', null);
		if (!$session) {
			$session = date('Ymd');
		}
		$res = Match::updateMatches($session);
		return response()->json(Common::dataFormat($res['status'], $res['msg']));
	}

	/**
	 * 更新比赛结果数据
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function updateMatchResult()
	{
		$session = \request()->input('session', null);
		if (!$session) {
			$session = date('Ymd', strtotime('-1 day'));
		}
		$res = $this->model->getMatchesResult($session);
		return response()->json(Common::dataFormat($res['status'], $res['msg']));
	}

	/**
	 * 筛选用户
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|\think\response\View
	 */
	public function pickUser(){
	    if(\request()->ajax()){
	        $session = date('Ymd');
	        $rate = \request()->input('rate',70);
	        $number = \request()->input('number',30);
	        $score = \request()->input('score',4);
	        $type = \request()->input('type','month');
	        $isGreat = \request()->input('isGreat',1);
	        $isGreat = $isGreat?true:false;
	        $userModel = new User();
	        $users = $userModel->pickUsers($session,$rate,$number,$score,$type,$isGreat);
	        return response()->json(['status' => config('statusInfo.status.success'), 'msg' => config('statusInfo.msg.success'), 'page' => 1, 'totalCount' => count($users), 'pages' => $users]);
        }else{
	        return view('admin.user.pick');
        }
    }

	/**
	 * 比赛推荐
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|\think\response\View
	 */
    public function recommendMatch(){
	    if(\request()->ajax()){
	    	$page = \request()->input('page',1);
		    $pageSize = \request()->input('pageSize',20);
		    $session = \request()->input('session','');
		    $rate = \request()->input('rate',70);
		    $number = \request()->input('number',30);
		    $score = \request()->input('score',4);
		    $type = \request()->input('type','month');
		    $session = $session?$session:date('Ymd');
		    $recordModel = new LotteryRecord();
		    $pageData = $recordModel->recommendMatches($page,$pageSize,$session,$rate,$number,$score,$type);
		    return response()->json(['status' => $pageData['status'], 'msg' => $pageData['msg'], 'page' => $page, 'totalCount' => $pageData['data']['totalCount'], 'pages' => $pageData['data']['pages']]);
	    }else{
		    return view('admin.lotteryRecord.recommend');
	    }
    }

	/**
	 * 获取比赛缓存数据
	 * @param string $session
	 * @return array|mixed
	 */
	private function getCacheMatch($session = '')
	{
		if (!$session) {
			$session = date('Ymd');
		}
		$matchInfo = Cache::get('matchesInfo');
		if (!$matchInfo) {
			return $this->saveCacheMatch($session);
		} else {
			if ($matchInfo['session'] != $session) {
				return $this->saveCacheMatch($session);
			}
			return $matchInfo['matches'];
		}
	}

	/**
	 * 缓存比赛数据
	 * @param string $session
	 * @return array|mixed
	 */
	private function saveCacheMatch($session = '')
	{
		if (!$session) {
			$session = date('Ymd');
		}
		$res = $this->model->updateMatches($session);
		if ($res['status'] == config('statusInfo.status.success')) {
			$matches = $this->model->getMatchesBySession($session);
			$data = [
				'session' => $session,
				'matches' => $matches,
			];
			Cache::put('matchesInfo', $data, 30);
			return $matches;
		}
		return [];
	}
}
